﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace BigPang.Render
{
    public class Effect : Renderable
    {
        int FrameFPS;
        int mFrameCount;
        int mStartTime;
        Bitmap mBitmap;

        Point mPosition;
        public Size Size { get; set; }
        bool mIsLoop;

        public Effect(string imageFileName, int frameFps, int frameCount, bool isLoop = false )
        {
            mBitmap = Bitmap.FromFile(imageFileName) as Bitmap;
            Size = new Size(mBitmap.Width / frameCount, mBitmap.Height);
            FrameFPS = frameFps;
            mFrameCount = frameCount;

            mStartTime = Environment.TickCount;
            mIsLoop = isLoop;
            mLayer = 2;
        }

        public Rectangle SrcRect
        {
            get
            {
                int nowTime = Environment.TickCount;
                float length = ((nowTime - mStartTime) / 1000.0f) * FrameFPS;

                int frame;
                if (mIsLoop)
                {
                    frame = (int)length % mFrameCount;
                }
                else
                {
                    if ((int)length > mFrameCount)
                    {
                        frame = 0;
                        UnregisterRender();
                    }
                    else
                    {
                        frame = (int)length;
                    }
                }

                return new Rectangle(new Point(frame * this.Size.Width, 0), this.Size);
            }
        }

        public void SetPosition(int x, int y)
        {
            mPosition.X = x;
            mPosition.Y = y;
        }

        public override void OnRender(System.Drawing.Graphics graph)
        {
            graph.DrawImage(mBitmap, new Rectangle(mPosition.X, mPosition.Y, this.Size.Width, this.Size.Height), SrcRect, GraphicsUnit.Pixel);
        }
    }
}
